#include "Render/PiccoloMesh.h"
#include "Render/PiccoloRenderContext.h"

#include "PiccoloApplication.h"

namespace Piccolo
{
    PiccoloMesh::PiccoloMesh(const std::vector<PiccoloVertex> &vertices, const std::vector<uint32_t> &indices)
    {
        if (vertices.empty()) return;

        PiccoloRenderContext* renderContext = PiccoloApplication::GetAppContext()->renderContext;
        PiccoloVKDevice* device = renderContext->GetDevice();

        mVertexCount = vertices.size();
        mIndexCount = indices.size();
        mVertexBuffer = std::make_shared<PiccoloVKBuffer>(device, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, sizeof(vertices[0]) * vertices.size(), (void*)vertices.data());
        if (mIndexCount > 0)
        {
            mIndexBuffer = std::make_shared<PiccoloVKBuffer>(device, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, sizeof(indices[0]) * indices.size(), (void*)indices.data());
        }
    }

    PiccoloMesh::~PiccoloMesh()
    {
    }

    void PiccoloMesh::Draw(VkCommandBuffer cmdBuffer)
    {
        // 绑定顶点缓冲区
        VkBuffer vertexBuffers[] = { mVertexBuffer->GetBuffer() };
        VkDeviceSize offsets[] = { 0 };
        vkCmdBindVertexBuffers(cmdBuffer, 0, 1, vertexBuffers, offsets);
        if (mIndexCount > 0)
        {
            // 绑定索引缓冲区
            vkCmdBindIndexBuffer(cmdBuffer, mIndexBuffer->GetBuffer(), 0, VK_INDEX_TYPE_UINT32);
            // 绘制
            vkCmdDrawIndexed(cmdBuffer, mIndexCount, 1, 0, 0, 0);
        }
        else
        {
            vkCmdDraw(cmdBuffer, mVertexCount, 1, 0, 0);
        }
    }
}
